
//
//  CommonTools.m
//  EVT_1.0
//
//  Created by huangchucai on 15/9/15.
//  Copyright (c) 2015年 ieschool. All rights reserved.


#import "CommonTools.h"
#import <sys/utsname.h>

@implementation CommonTools

/**
 方法：判断输入的汉字是否在 2-5个之间
 @param inputText 输入信息
 @return NSString 返回字符串
 */
+ (NSString *)inputChineseNumIn2And5:(NSString *)inputText
{
    NSInteger num = 0;
    for (int i = 0; i < inputText.length; i ++) {
        unichar ch = [inputText characterAtIndex:i];
        if (ch >= 0x4E00 && ch <= 0x9FA5) {
            num ++;
        }
    }
    if (num < 2) {
        return @"输入的姓名不能少于2个汉字";
    }
    else if ( num > 5){
        return @"输入的姓名不能多于5个汉字";
    }
    return nil;
}

/**
 方法：判断输入的内容是否为纯英文字母（是否包含有汉字）
 @param inputText 输入信息
 @return BOOL     返回是否成功
 */
+ (BOOL)inputContainsEnglish:(NSString *)inputText
{
    for (int i = 0; i < inputText.length; i ++) {
        unichar ch = [inputText characterAtIndex:i];
        if (  !(ch >= 0x4E00 && ch <= 0x9FA5) ) {
            return YES;
        }
    }
    return NO;
}

/**
 方法：判断输入的内容是否为纯汉字（是否包含有英文字母）
 @param inputText 输入信息
 @return BOOL     返回是否成功
 */

+ (BOOL)inputContainsChinese:(NSString *)inputText
{
    for (int i = 0; i < inputText.length; i ++) {
        unichar ch = [inputText characterAtIndex:i];
        if (ch >= 0x4E00 && ch <= 0x9FA5) {
            return YES;
        }
    }
    return NO;
}

/**
 方法：判断输入的内容是否为纯数字
 @param  inputText 输入信息
 @return BOOL      返回是否成功
 */

+ (BOOL)inputContainsNumber:(NSString *)inputText
{
    inputText = [inputText stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(inputText.length > 0) {
    return NO;
    }
    return YES;
}

/**
 方法：判断输入的号码是否为合法的手机号码
 @param  phoneStr  手机号码
 @return BOOL      返回是否成功
 */

+ (BOOL)isLegalPhoneNumber:(NSString* )phoneStr
{                                       //' ' == '1'
    if (phoneStr.length != 11 || [phoneStr characterAtIndex:0] != 48+1) {
        return NO;
    }
    char secondChar = [phoneStr characterAtIndex:1];
    if ( secondChar == 48+3 || secondChar == 48+8 || secondChar == 48+5 )
    {
        if (secondChar == 48 + 5)
        {
            char thirdChar = [phoneStr characterAtIndex:2];
            if (thirdChar == 48 + 4) {
                return NO;
            }
        }
    return YES;
    }
    return NO;
}

/**
 方法：判断输入的手机号码是不是正确的
 @param  phoneNumber  手机号码
 @return NSString     返回是否成功
 */

+ (NSString *)isLegalPhoneNumber2:(NSString* )phoneNumber
{
    if (phoneNumber.length < 11 )
    {
        return @"手机号长度不能少于11位";
    }
    else if (phoneNumber.length > 11)
    {
        return @"手机号长度不能多于11位";
    }
    else
    {
        /**
         * 所有手机段正则表达式
         */
        NSString *CM_NUM = @"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:phoneNumber];
    
       if (isMatch1)
       {
            return nil;
        }else
       {
       return @"请输入正确的电话号码";
       }
    }
    return nil;

}

/**
 方法：判断输入的银行卡是不是正确的
 @param  cardNo       银行卡号
 @return NSString     返回是否成功
 */
+(BOOL)checkCardNo:(NSString*)cardNo
{
    int oddsum = 0;     //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[cardNo length];
    int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength -1 ; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1 ) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else
        return NO;
}

/**
 方法：判断输入的身份证是不是正确的
 @param  identityString    身份号
 @return NSString          返回是否成功
 */

+(BOOL)checkIdentityStringValid:(NSString *)identityString
{
        //长度不为18的都排除掉
        if (identityString.length!=18)
        {
            return NO;
        }
        //校验格式
        NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
        NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
        BOOL flag = [identityCardPredicate evaluateWithObject:identityString];
        
        if (!flag) {
            return flag;    //格式错误
        }else {
            //格式正确在判断是否合法
            
            //将前17位加权因子保存在数组里
            NSArray * idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
            
            //这是除以11后，可能产生的11位余数、验证码，也保存成数组
            NSArray * idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
            
            //用来保存前17位各自乖以加权因子后的总和
            NSInteger idCardWiSum = 0;
            for(int i = 0;i < 17;i++)
            {
                NSInteger subStrIndex = [[identityString substringWithRange:NSMakeRange(i, 1)] integerValue];
                NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
                
                idCardWiSum+= subStrIndex * idCardWiIndex;
                
            }
            
            //计算出校验码所在数组的位置
            NSInteger idCardMod=idCardWiSum%11;
            
            //得到最后一位身份证号码
            NSString * idCardLast= [identityString substringWithRange:NSMakeRange(17, 1)];
            
            //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
            if(idCardMod==2)
            {
                if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"])
                {
                    return YES;
                }else
                {
                    return NO;
                }
            }else{
                //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]])
                {
                    return YES;
                }
                else
                {
                    return NO;
                }
            }
        }

}
//判断输入的号码是否为合法的密码(字母，数字，下划线组成，6-18位)
+ (BOOL)isLegalPassword:(NSString* )password{
    
    if (password.length < 6 || password.length > 18) {
        return NO;
    }
    for (int i = 0; i < password.length; i ++)
    {
        unichar ch = [password characterAtIndex:i];
        if ( !( (ch >='a' && ch <='z')  ||
                (ch >='A' && ch <= 'Z') ||
                (ch >= '0' && ch <='9') ||
                ch == '_'))
        {
            return NO;
        }
    }    
    return YES;
}

/** 随机产生一个32位长度的字符串 */
+ (NSString *)ret32BitString{
    char data[32] = {0};
    for( int x = 0; x < 32; data[x++]=(char)('A'+arc4random_uniform(26)))
        ;
    NSString *str = [[NSString alloc]initWithBytes:data length:32 encoding:NSUTF8StringEncoding];
    return str;
}

//返回36位大小写字母和数字和中划线
+(NSString *)return36LetterAndNumber{
    //定义一个包含数字，大小写字母的字符串
    NSString * strAll = @"0123456789abcdefghijklmnopqrstuvwxyz-";
    //定义一个结果
    NSString * result = [[NSMutableString alloc]initWithCapacity:36];
    for (int i = 0; i < 36; i++)
    {
        //获取随机数
        NSInteger index = arc4random() % (strAll.length-1);
        char tempStr = [strAll characterAtIndex:index];
        result = (NSMutableString *)[result stringByAppendingString:[NSString stringWithFormat:@"%c",tempStr]];
    }
    
    return result;
}
//返回位大小写字母和数字
+(NSString *)returnLetterAndNumber:(int)count{
    //定义一个包含数字，大小写字母的字符串
    NSString * strAll = @"0123456789abcdefghijklmnopqrstuvwxyz";
    //定义一个结果
    NSString * result = [[NSMutableString alloc]initWithCapacity:count];
    for (int i = 0; i < count; i++)
    {
        //获取随机数
        NSInteger index = arc4random() % (strAll.length-1);
        char tempStr = [strAll characterAtIndex:index];
        result = (NSMutableString *)[result stringByAppendingString:[NSString stringWithFormat:@"%c",tempStr]];
    }
    
    return result;
}


//返回位数字
+(NSString *)returnNumber:(int)count{
    //定义包含数字字符串
    NSString * strAll = @"0123456789";
    //定义一个结果
    NSString * result = [[NSMutableString alloc]initWithCapacity:count];
    for (int i = 0; i < count; i++)
    {
        //获取随机数
        NSInteger index = arc4random() % (strAll.length-1);
        char tempStr = [strAll characterAtIndex:index];
        result = (NSMutableString *)[result stringByAppendingString:[NSString stringWithFormat:@"%c",tempStr]];
    }
    
    return result;

}

//获取手机型号
+(NSString *)iphoneType
{
    struct utsname systemInfo;
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    
    if ([platform isEqualToString:@"iPod1,1"])  return @"iPod Touch 1G";
    
    if ([platform isEqualToString:@"iPod2,1"])  return @"iPod Touch 2G";
    
    if ([platform isEqualToString:@"iPod3,1"])  return @"iPod Touch 3G";
    
    if ([platform isEqualToString:@"iPod4,1"])  return @"iPod Touch 4G";
    
    if ([platform isEqualToString:@"iPod5,1"])  return @"iPod Touch 5G";
    
    if ([platform isEqualToString:@"iPad1,1"]) return @"iPad 1G";
    
    if ([platform isEqualToString:@"iPad2,1"])  return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,3"])  return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,5"])  return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,6"])  return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,7"])  return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad3,1"])  return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,2"])  return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,3"])  return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,4"])  return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,5"])  return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,3"]) return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,6"]) return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator";
    
    if ([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";
    
    return platform;

}

//获取GUID
+(NSString *)getUniqueStrByUUID
{
    CFUUIDRef   uuidObj = CFUUIDCreate(nil);//create a new UUID
    //get the string representation of the UUID
    NSString *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    CFRelease(uuidObj);
    return uuidString ;
}

/*
 
 方法名:计算字节
 @param NSString str
 @reture int

 */

+(int)convertToByte:(NSString*)str
{
    NSStringEncoding gbkEncoding=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSInteger formaSize =  [str lengthOfBytesUsingEncoding:gbkEncoding];
    return (int)formaSize;
}


/// 判断字符串是否为空 为空返回空字符串 不为空返回自己
/// - Parameter str: 字符串
+(NSString *)checkStringIsNull:(NSString *)str{
    if(str.length>0){
        return str;
    }else{
        return @"";
    }
}


/// 返回提示框 带取消和确定按钮的
/// - Parameters:
///   - message: 提示文本
///   - confirm: 确定Block
///   - cancel: 取消Block
+(UIAlertController *)alertWithMessage:(NSString *)message confirmBlock:(void (^)(void))confirm cancelBlock:(void (^)(void))cancel{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        cancel();
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        confirm();
    }]];
    return alertController;
}

/// 返回提示框 带确定按钮的
/// - Parameters:
///   - message: 提示文本
///   - confirm: 确定Block
+(UIAlertController *)alertSureWithMessage:(NSString *)message confirmBlock:(void (^)(void))confirm{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        confirm();
    }]];
    return alertController;
}

@end
